from django.urls import reverse
from django.shortcuts import redirect
from myadmin.models import Shop, Category, Product
from django.http import HttpResponse, JsonResponse


def add(request):
    # 添加购物车操作
    # 尝试获取购物车信息
    cartlist = request.session.get('mobile_cartlist', {})
    # 获取要购买的菜品信息
    pid = request.GET.get('pid', None)
    if pid is not None:
        product = Product.objects.get(id=pid).toDict()
        product['num'] = 1

        # 判断当前购物车中是否存在放放进购物车的菜品
        if pid in cartlist:
            cartlist[pid]['num'] += 1  # 增加购买量
        else:
            cartlist[pid] = product  # 放进购物车
        # 将cartlist放入session
        request.session['mobile_cartlist'] = cartlist
    # 响应json格式购物车数据
    return JsonResponse({'cartlist': cartlist})


def delete(request):
    # 删除购物车操作
    # 从session中获取购物车信息
    pid = request.GET.get('pid', None)
    cartlist = request.session.get('mobile_cartlist', {})
    del cartlist[pid]
    # 将cartlist放入session
    request.session['cartlist'] = cartlist
    # 响应json格式购物车数据
    return JsonResponse({'cartlist': cartlist})


def clear(request):
    # 清空购物车操作
    request.session['mobile_cartlist'] = {}
    # 响应json格式购物车数据
    return JsonResponse({'cartlist': {}})


def change(request):
    # 购物车的更改
    # 从session中获取购物车信息
    cartlist = request.session.get('mobile_cartlist', {})
    pid = request.GET.get('pid', 0)
    m = int(request.GET.get('num', 1))
    if m < 1:
        m = 1
    cartlist[pid]['num'] = m
    request.session['mobile_cartlist'] = cartlist
    # 响应json格式购物车数据
    return JsonResponse({'cartlist': cartlist})
